package com.kj.xuyuan.home;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kj.xuyuan.R;
import com.kj.xuyuan.adapter.RecommendAndNearAdapter;
import com.kj.xuyuan.base.BaseFragment;
import com.kj.xuyuan.base.BaseModel;
import com.kj.xuyuan.base.Constants;
import com.kj.xuyuan.http.JsonCallback;
import com.kj.xuyuan.http.OkGoUtil;
import com.kj.xuyuan.http.UrlConstants;
import com.kj.xuyuan.mine.HomePageActivity;
import com.kj.xuyuan.model.RecommendAndNearBean;
import com.kj.xuyuan.model.UserInfoBean;
import com.kj.xuyuan.pop.SelectFriendAddressPopWindow;
import com.kj.xuyuan.util.LogUtils;
import com.kj.xuyuan.util.SPUtils;
import com.kj.xuyuan.util.ToastUtil;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class RecommendFragment extends BaseFragment {

    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.rv_recommend)
    RecyclerView rvRecommend;
    @BindView(R.id.sml_recommend)
    SmartRefreshLayout smlRecommend;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;

    private int type; //1推荐  2附近
    private List<RecommendAndNearBean> data;
    private RecommendAndNearAdapter adapter;
    private String province;
    private String start_age,end_age;
    private int page = 1;
    private List<String> ageList;

    public static RecommendFragment newInstance(int type) {
        Bundle arguments = new Bundle();
        arguments.putInt("type", type);
        RecommendFragment fl = new RecommendFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.layout_fragment_recommend;
    }

    @Override
    protected void initView() {
        type = getArguments().getInt("type");

        initAgeList();

        initRecyclerView();
        getData();
    }

    private void initAgeList() {
        ageList = new ArrayList<>();
        for(int i = 18 ;i <=70 ;i++){
            ageList.add(i+"");
        }
    }

    private void initRecyclerView() {
        data = new ArrayList<>();
        adapter = new RecommendAndNearAdapter(type);
        rvRecommend.setLayoutManager(new LinearLayoutManager(getContext()));
        rvRecommend.setAdapter(adapter);
        adapter.setNewData(data);

        smlRecommend.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getData();
            }
        });

        smlRecommend.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page ++;
                getData();
            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.tv_like_or_chat:
                        if(data.get(position).getIs_like() == 0){
                            like(position);
                        }else{
                            //聊天页
                        }
                        break;
                }
            }
        });

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HomePageActivity.actionStar(getContext(),data.get(position).getId());
            }
        });
    }

    private void like(int position) {
        Map map = new HashMap();
        map.put("for_user_id",data.get(position).getUser().getId());
        OkGoUtil.postRequest(getContext(), UrlConstants.LIKE, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        data.get(position).setIs_like(data.get(position).getIs_like() == 0 ? 1 : 0);
                        adapter.notifyDataSetChanged();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void getData() {
        Map map = new HashMap();
        map.put("province", province);
        map.put("start_age", start_age);
        map.put("end_age", end_age);
        map.put("type", type+"");
        if(type == 2){
            map.put("lat", Constants.LATITUDE);
            map.put("lng", Constants.LONGITUDE);
        }
        map.put("page", page+"");

        OkGoUtil.postRequest(getContext(), UrlConstants.RECOMMEND_AND_NEAR, map, new JsonCallback<BaseModel<List<RecommendAndNearBean>>>() {
            @Override
            public void onSuccess(Response<BaseModel<List<RecommendAndNearBean>>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        if(page == 1){
                            data.clear();
                        }
                        data.addAll(response.body().getData());
                        adapter.notifyDataSetChanged();
                        llNoData.setVisibility(data.size() == 0 ? View.VISIBLE : View.GONE);
                    }else{
                        ToastUtil.showToast(getContext(),response.body().getMsg());
                    }
                    smlRecommend.finishRefresh();
                    smlRecommend.finishLoadMore();
                }
            }

            @Override
            public void onError(Response<BaseModel<List<RecommendAndNearBean>>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
                llNoData.setVisibility(data.size() == 0 ? View.VISIBLE : View.GONE);
                smlRecommend.finishRefresh();
                smlRecommend.finishLoadMore();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tv_location, R.id.tv_age})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_location:
                popSelectFriendAddressWindow();
                break;
            case R.id.tv_age:
                showPickerView();
                break;
        }
    }

    private void popSelectFriendAddressWindow() {
        SelectFriendAddressPopWindow popWindow = new SelectFriendAddressPopWindow(getActivity());
        popWindow.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.BOTTOM,0,0);
        popWindow.setAnimationStyle(R.style.popwindow_center_anim_style);
        popWindow.setSelectProvinceListener(new SelectFriendAddressPopWindow.SelectProvinceListener() {
            @Override
            public void selectedProvince(String selectProvinceName) {
                if(selectProvinceName.equals("全部")){
                    province = null;
                }else{
                    province = selectProvinceName;
                }
                tvLocation.setText(province);
                page = 1;
                getData();
            }
        });
    }

    private void showPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                start_age = ageList.get(options1);
                end_age = ageList.get(options2);
                tvAge.setText(start_age+"-"+end_age);
                page = 1;

                getData();
            }

        }).setTitleText("年龄选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setNPicker(ageList,ageList,null);
        pvOptions.show();
    }
}
